package titt.io.encoding;

import titt.type.Type;

public class CompositeDecoder implements Decoder {

	private static final Decoder EMPTY = new Decoder() {

		@Override
		public Object decode(Type t, byte[] b) {
			return null;
		}

		@Override
		public boolean isDecodeable(Type t) {
			return false;
		}
		
	};
	
	private Decoder pri, sec;
	
	public CompositeDecoder(Decoder... decs) {
		this(decs.length == 0? new Decoder[]{EMPTY} : decs, 0);
	}
	
	private CompositeDecoder(Decoder[] decs, int off) {
		this(decs[off], off < decs.length - 1? new CompositeDecoder(decs, off + 1) : EMPTY);
	}
	
	private CompositeDecoder(Decoder pri, Decoder sec) {
		this.pri = pri;
		this.sec = sec;
	}
	
	@Override
	public Object decode(Type t, byte[] b) {
		if(pri.isDecodeable(t))
			return pri.decode(t, b);
		else
			return sec.decode(t, b);
	}
	
	@Override
	public boolean isDecodeable(Type t) {
		return pri.isDecodeable(t) || sec.isDecodeable(t);
	}	

}
